import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { toast } from 'react-toastify';
import { 
  FaCog, FaServer, FaRobot, FaKey, FaEye, FaEyeSlash, 
  FaUndo, FaSave 
} from 'react-icons/fa';
import NavBar from '../components/NavBar';
import './AISettings.css';
import './styles.css';

function AISettings() {
  const [settings, setSettings] = useState({
    apiKey: '',
    baseUrl: '',
    model: ''
  });
  
  const [userSettings, setUserSettings] = useState({
    apiKey: '',
    baseUrl: '',
    model: ''
  });
  
  // 保存初始的用户设置，用于比较是否有更改
  const [originalUserSettings, setOriginalUserSettings] = useState({
    apiKey: '',
    baseUrl: '',
    model: ''
  });
  
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [showApiKey, setShowApiKey] = useState(false);

  // 获取当前设置和用户自定义设置
  useEffect(() => {
    const fetchSettings = async () => {
      try {
        // 获取系统默认设置
        const response = await axios.get('/api/ai/settings');
        
        // 获取用户自定义设置
        const userResponse = await axios.get('/api/ai/user-settings');
        
        setSettings({
          apiKey: response.data.defaultApiKey || '',
          baseUrl: response.data.defaultBaseUrl || '',
          model: response.data.defaultModel || ''
        });
        
        const userData = {
          apiKey: userResponse.data.apiKey || '',
          baseUrl: userResponse.data.baseUrl || '',
          model: userResponse.data.model || ''
        };
        
        setUserSettings(userData);
        // 保存初始设置以便比较
        setOriginalUserSettings(userData);
        
      } catch (error) {
        console.error('获取AI设置失败:', error);
        toast.error('获取设置信息失败');
      } finally {
        setLoading(false);
      }
    };
    
    fetchSettings();
  }, []);

  // 保存设置
  const handleSaveSettings = async () => {
    setSaving(true);
    
    try {
      await axios.post('/api/ai/user-settings', userSettings);
      toast.success('AI设置已保存');
      setOriginalUserSettings({...userSettings}); // 更新原始设置
    } catch (error) {
      console.error('保存AI设置失败:', error);
      toast.error('保存设置失败');
    } finally {
      setSaving(false);
    }
  };

  // 重置为系统默认设置
  const handleResetSettings = () => {
    // 重置为最初从服务器获取的用户设置
    setUserSettings({...originalUserSettings});
    toast.info('已重置为初始设置');
  };

  // 检测是否有更改
  const hasChanges = () => {
    // 检查当前设置与初始设置是否有变化
    const hasChanged = 
      userSettings.apiKey !== originalUserSettings.apiKey ||
      userSettings.baseUrl !== originalUserSettings.baseUrl ||
      userSettings.model !== originalUserSettings.model;
    
    // 确保至少API服务器地址或模型名称有一个不为空
    const hasValidSettings = 
      userSettings.baseUrl.trim() !== '' || 
      userSettings.model.trim() !== '';
    
    // 只有当设置有变化且有效时才能保存
    return hasChanged && hasValidSettings;
  };

  if (loading) {
    return (
      <div className="page-container">
        <NavBar />
        <div className="ai-loading-container">
          <div className="ai-loading-spinner"></div>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="page-container">
      <NavBar />
      
      <div className="ai-settings-container">
        <div className="ai-decoration-circle top-right"></div>
        <div className="ai-decoration-circle bottom-left"></div>
        
        <div className="ai-settings-header">
          <h1><FaCog style={{marginRight: '10px'}} /> AI设置</h1>
          <p className="ai-settings-description">
            自定义AI处理设置，包括API密钥、服务器URL和模型选择，让您的AI体验更加个性化
          </p>
        </div>
        
        <div className="ai-settings-content">
          <div className="ai-settings-box system-settings">
            <h2><FaServer /> 系统默认设置</h2>
            <div className="ai-settings-info">
              <div className="ai-setting-item">
                <span className="ai-setting-label">默认API服务器:</span>
                <span className="ai-setting-value">{settings.baseUrl || '未设置'}</span>
              </div>
              <div className="ai-setting-item">
                <span className="ai-setting-label">默认模型:</span>
                <span className="ai-setting-value">{settings.model || '未设置'}</span>
              </div>
              <div className="ai-setting-item">
                <span className="ai-setting-label">默认API密钥:</span>
                <span className="ai-setting-value">{settings.apiKey ? '已配置' : '未设置'}</span>
              </div>
            </div>
          </div>
          
          <div className="ai-settings-box">
            <h2><FaCog /> 个人自定义设置</h2>
            <p className="ai-settings-note">
              这些设置将优先于系统默认设置使用。留空表示使用系统默认设置。
            </p>
            
            <div className="ai-form-group">
              <label htmlFor="baseUrl"><FaServer /> API服务器地址</label>
              <input
                type="text"
                id="baseUrl"
                placeholder="例如: http://localhost:11434/v1"
                value={userSettings.baseUrl}
                onChange={(e) => setUserSettings({...userSettings, baseUrl: e.target.value})}
                className="ai-form-control"
              />
              <div className="ai-form-hint">
                本地Ollama服务器通常为: http://localhost:11434/v1
              </div>
            </div>
            
            <div className="ai-form-group">
              <label htmlFor="model"><FaRobot /> AI模型名称</label>
              <input
                type="text"
                id="model"
                placeholder="例如: deepseek:7b"
                value={userSettings.model}
                onChange={(e) => setUserSettings({...userSettings, model: e.target.value})}
                className="ai-form-control"
              />
              <div className="ai-form-hint">
                常用模型: deepseek:7b, llama2:7b, chatgpt-3.5-turbo 等
              </div>
            </div>
            
            <div className="ai-form-group">
              <label htmlFor="apiKey"><FaKey /> API密钥</label>
              <div className="ai-password-input-container">
                <input
                  type={showApiKey ? "text" : "password"}
                  id="apiKey"
                  placeholder="API密钥"
                  value={userSettings.apiKey}
                  onChange={(e) => setUserSettings({...userSettings, apiKey: e.target.value})}
                  className="ai-form-control"
                />
                <button 
                  type="button"
                  className="ai-show-password-btn"
                  onClick={() => setShowApiKey(!showApiKey)}
                >
                  {showApiKey ? <FaEyeSlash /> : <FaEye />}
                </button>
              </div>
              <div className="ai-form-hint">
                对于本地Ollama服务器，可以留空
              </div>
            </div>
            
            <div className={`ai-settings-validation ${!hasChanges() ? 'ai-validation-error' : 'ai-validation-success'}`}>
              {!hasChanges() ? (
                <>
                  <FaRobot style={{marginRight: '8px'}} />
                  请修改设置并确保API服务器地址或模型名称至少填写一项
                </>
              ) : (
                <>
                  <FaRobot style={{marginRight: '8px'}} />
                  设置已修改，可以保存
                </>
              )}
            </div>
            
            <div className="ai-settings-actions">
              <button 
                className="ai-btn ai-btn-secondary" 
                onClick={handleResetSettings}
                disabled={!hasChanges()}
              >
                <FaUndo style={{marginRight: '5px'}} /> 重置为初始设置
              </button>
              <button 
                className="ai-btn ai-btn-primary" 
                onClick={handleSaveSettings}
                disabled={saving || !hasChanges()}
                title={!hasChanges() ? "请修改设置并确保API服务器地址或模型名称不为空" : "保存您的设置"}
              >
                <FaSave style={{marginRight: '5px'}} /> {saving ? '保存中...' : '保存设置'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default AISettings; 